package com.candy.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * 2021/11/16
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    // 获取日志
    private final Logger logger =
            LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    // 标识此方法可以进行异常处理
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        // 通过request请求可以获取出现异常的url
        logger.error("Request URL : {}，Exception ：{}",request.getRequestURL(),e);
        // 如果该类上存在@ResponseStatus这个注解，证明不为null  就返回该类自定义的异常
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",e);
        mv.setViewName("error/error");// 希望返回的页面

        return mv;
    }
}
